package com.fanbai.score.common.fragment;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.DownloadListener;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.fanbai.score.R;
import com.fanbai.score.common.base.BaseFragment;
import com.fanbai.score.common.base.MyApplication;

/**
 * Created by acer on 2017/6/17.
 */

public class WebViewFragment extends BaseFragment{

    private String bar_name;
    private ProgressBar pb; // webview加载进度条
    private WebView webview;
    private xWebChromeClient xwebchromeclient;

    private String mArgument = "";
    private static final String ARGUMENT = "url";
    private static String title = "";

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static WebViewFragment newInstance(String url, String title) {
        WebViewFragment fragment = new WebViewFragment();
        Bundle args = new Bundle();
        args.putString(ARGUMENT, url);
        args.putString("title", title);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null){
            title = bundle.getString("title");
            mArgument = bundle.getString(ARGUMENT);
        }

    }

    public WebViewFragment() {
    }

    @Override
    protected int getLayoutID() {
        return R.layout.fragment_webview;
    }

    @Override
    public String getTitleName() {
        return title;
    }

    @Override
    public void iniTitleLeft(ImageView tv) {

    }

    @Override
    public void iniTitleRight(TextView tv) {

    }

    @Override
    protected void initView(View view) {
        initwidget(view);

        webview.getSettings().setDisplayZoomControls(false);
        webview.getSettings().setLoadsImagesAutomatically(true); // 支持自动加载图片
        synCookies(ctx, mArgument);
        webview.loadUrl(mArgument);
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initListener() {

    }

    private void initwidget(View view) {
        // TODO Auto-generated method stub
        pb = (ProgressBar) view.findViewById(R.id.pb);
        pb.setMax(100);

        webview = (WebView) view.findViewById(R.id.video_webview);

        WebSettings ws = webview.getSettings();
        ws.setBuiltInZoomControls(true);// 隐藏缩放按钮
        ws.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);// 排版适应屏幕
        ws.setUseWideViewPort(true);// 可任意比例缩放
        ws.setLoadWithOverviewMode(true);// setUseWideViewPort方法设置webview推荐使用的窗口。setLoadWithOverviewMode方法是设置webview加载的页面的模式。
        ws.setSavePassword(true);
        ws.setSaveFormData(true);// 保存表单数据
        ws.setJavaScriptEnabled(true);
        ws.setGeolocationEnabled(true);// 启用地理定位
        ws.setGeolocationDatabasePath("/data/data/org.itri.html5webview/databases/");// 设置定位的数据库路径
        ws.setDomStorageEnabled(true);

        webview.getSettings().setJavaScriptEnabled(true);
        webview.getSettings().setSupportZoom(true);
        webview.getSettings().setBuiltInZoomControls(true);
        webview.getSettings().setDefaultZoom(WebSettings.ZoomDensity.FAR);

        xwebchromeclient = new xWebChromeClient();
        webview.setWebChromeClient(xwebchromeclient);
        webview.setWebViewClient(new xWebViewClientent());
        webview.setDownloadListener(new MyWebViewDownLoadListener());
    }

    /**
     * 处理Javascript的对话框、网站图标、网站标题以及网页加载进度等
     *
     * @author
     */
    public class xWebChromeClient extends WebChromeClient {

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            pb.setProgress(newProgress);
            if (newProgress == 100) {
                pb.setVisibility(View.GONE);
            }
            super.onProgressChanged(view, newProgress);
        }
    }


    /**
     * 处理各种通知、请求等事件
     *
     * @author
     */
    public class xWebViewClientent extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Log.i("webviewtest", "shouldOverrideUrlLoading: " + url);
            //界面内跳转的监听处理，注意判断顺序

            //跳转本地应用
            if (url.startsWith("intent://")) {
                Intent intent;
                try {
                    intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
                    intent.addCategory("android.intent.category.BROWSABLE");
                    intent.setComponent(null);
//					intent.setSelector(null);
                    startActivity(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(getActivity(), "应用未安装或未找到", Toast.LENGTH_LONG).show();
                }
                return true;
            }
            if (!(url.startsWith("http") || url.startsWith("https"))) {
                return true;
            }
            view.loadUrl(url);
            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            String t = view.getTitle();
            if (null == t || t.equals("")) {
                return;
            }
            if (t.length() > 10) {
                t = t.substring(0, 10) + "...";
            }
            if (null == bar_name || "".equals(bar_name)) {
               setTvTitle(t);
            }
        }
    }

    private class MyWebViewDownLoadListener implements DownloadListener {
        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype,
                                    long contentLength) {
            if (url.contains(".apk")){
                Uri uri = Uri.parse(url);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
            }
        }
    }

    /** 
      * 同步一下cookie 
      */
    public static void synCookies(Context context, String url){
        CookieSyncManager.createInstance(context);
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        cookieManager.removeSessionCookie();//移除  PHPSESSID=clu0i8gipfvpsasl8sfa4ee1c2
        String oldCookie = MyApplication.getInstanti().getCookieStore().getCookies().toString();
        oldCookie = oldCookie.substring(1,oldCookie.length()-1);
        cookieManager.setCookie(url, oldCookie);//cookies是在HttpClient中获得的cookie  
        if (android.os.Build.VERSION.SDK_INT > 21) {
            CookieManager.getInstance().flush();
        } else {
            CookieSyncManager.getInstance().sync();
        }
        String newCookie = cookieManager.getCookie(url);
    }

}
